package com.nodecollege.cloud.common.utils;

import com.nodecollege.cloud.common.enums.ErrorEnum;
import com.nodecollege.cloud.common.exception.UpmsException;
import com.nodecollege.cloud.common.model.LoginUser;
import lombok.Data;

/**
 * 线程共享数据
 *
 * @author LC
 * @date 18:33 2019/12/3
 **/
@Data
public class ThreadUserUtils {

    private static final ThreadLocal<LoginUser> THREAD_LOCAL_UER = new ThreadLocal<>();

    private ThreadUserUtils() {
    }

    /**
     * 清除线程中的用户数据
     **/
    public static void resetLoginUser() {
        THREAD_LOCAL_UER.remove();
    }

    /**
     * 设置登陆用户信息
     **/
    public static void setLoginUser(LoginUser loginUser) {
        THREAD_LOCAL_UER.set(loginUser);
    }

    /**
     * 获取登陆用户信息
     **/
    public static LoginUser getLoginUserThrow() {
        LoginUser loginUser = getLoginUser();
        if (NCUtils.isNullOrEmpty(loginUser)) {
            throw new UpmsException(ErrorEnum.LOGIN_TIME_OUT);
        }
        return loginUser;
    }

    /**
     * 获取登陆用户信息
     **/
    public static LoginUser getLoginUser() {
        return THREAD_LOCAL_UER.get();
    }
}
